package com.chinawlx.wlxteacher.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chinawlx.wlxteacher.R;
import com.chinawlx.wlxteacher.network.WLXHttpRxHelper;
import com.chinawlx.wlxteacher.network.bean.WLXCourseFinishedBean;
import com.chinawlx.wlxteacher.network.bean.WLXSingleCourseBean;
import com.chinawlx.wlxteacher.utils.WLXDateUtil;
import com.chinawlx.wlxteacher.utils.WLXGreenDaoUtil;
import com.chinawlx.wlxteacher.utils.WLXLogUtil;
import com.chinawlx.wlxteacher.utils.WLXTeacherConstant;
import com.chinawlx.wlxteacher.widget.WLXCustomToast;
import com.chinawlx.wlxteacher.wlx_schedule;
import com.chinawlx.wlxteacher.wlx_scheduleDao;
import com.chinawlx.wlxteacher.wlx_student_study;
import com.chinawlx.wlxteacher.wlx_student_studyDao;
import com.google.gson.Gson;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import rx.Subscriber;

/**
 * 课堂详情
 * <p>
 * Created by wlx on 16/8/18.
 */
public class WLXClazzRoomDetailActivity extends WLXBaseActivity implements View.OnClickListener {
    @BindView(R.id.iv_back_clazzroom_detail)
    ImageView backBtn;
    @BindView(R.id.rl_clazzroom_call_roll)
    RelativeLayout callrollBtn;
    @BindView(R.id.rl_course_content)
    RelativeLayout contentBtn;
    @BindView(R.id.tv_inclazz_clazzroom)
    TextView inClazzTv;
    @BindView(R.id.tv_leave_clazzroom)
    TextView leaveTv;
    @BindView(R.id.tv_truant_clazzroom)
    TextView truantTv;
    @BindView(R.id.prepareContent)
    TextView mPrepareContent;
    @BindView(R.id.btn_end_course)
    Button endCourseBtn;
    @BindView(R.id.ll_appraise)
    LinearLayout appraiseLayout;
    //    private long openingDate;
//    private long closingDate;
    private long currentTime;
    private String gradeId;
    private String scheduleId;
//    private String studentIds;
    private int isAddition;
    private String btnContent;
    private List<wlx_schedule> singleScheduleList;
    private String prepare_content;
    private int is_finished;
    private Long opening_date;
    private Long closing_date;
    private String addition_student_ids;
    private Integer is_study;

    private int studyNum=0;
    private int leaveNum=0;
    private int truantNum=0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_clazzroom_detail);
        ButterKnife.bind(this);
        backBtn.setOnClickListener(this);
        callrollBtn.setOnClickListener(this);
        contentBtn.setOnClickListener(this);
        endCourseBtn.setOnClickListener(this);
        initData();
    }

    private void initView() {
        //统计出勤,请假,旷课人数
        if (is_study==1) {
            List<wlx_student_study> studyList = WLXGreenDaoUtil.getStudentStudyDao().queryBuilder()
                    .where(wlx_student_studyDao.Properties.Grade_id.eq(gradeId),
                            wlx_student_studyDao.Properties.Schedule_id.eq(scheduleId)).list();
            for (wlx_student_study studentStudy : studyList) {
                String code = studentStudy.getStudy_status_code();
                WLXLogUtil.printE("code: "+code);
                switch (code){
                    case "study":
                        studyNum++;
                        break;
                    case "leave":
                        leaveNum++;
                        break;
                    case "truant":
                        truantNum++;
                        break;
                }
            }
            inClazzTv.setText(studyNum+"");
            leaveTv.setText(leaveNum+"");
            truantTv.setText(truantNum+"");
        }
        //判断课程内容是否为空，如果不为空，点击时提示已经发布课程内容
        if (TextUtils.isEmpty(prepare_content)) {
            mPrepareContent.setText("请添加学习内容");
        } else {
            mPrepareContent.setText(prepare_content);
        }
        //未上课时不显示课后评价
        if (closing_date>currentTime) {
            appraiseLayout.setVisibility(View.GONE);
        } else {
            appraiseLayout.setVisibility(View.VISIBLE);
        }
        /*
         * 当课程的is_finished字段为1时，显示已结课，按钮不可点击；
         * 当课程的is_finished字段为0并且课程的closing_date比当前时间晚，点击后提示不能结课；
         * 当可以结课时，点击结课按钮，发送结课请求，当返回Code = 0时，显示已结课，结课按钮不可点击，
         * 同时根据课程id发送刷新单个课程的请求，返回到课程管理界面刷新单行cell
         */
        if (is_finished == 1) {
            endCourseBtn.setText("已结课");
            endCourseBtn.setClickable(false);
        } else if (is_finished == 0 && closing_date > currentTime) {
            endCourseBtn.setText("结课");
            endCourseBtn.setClickable(true);
        }
    }

    private void initData() {
        Intent intent = getIntent();
        gradeId = intent.getStringExtra(WLXTeacherConstant.GRADE_ID);
        scheduleId = intent.getStringExtra(WLXTeacherConstant.SCHEDULE_ID);
        WLXLogUtil.printE("schedule_id: "+scheduleId);
        WLXLogUtil.printE("grade_id: "+gradeId);
//        prepareContent = intent.getStringExtra(WLXTeacherConstant.PREPARE_CONTENT);
//        isStudy = intent.getIntExtra(WLXTeacherConstant.IS_STUDY, 0);
//        openingDate = intent.getLongExtra(WLXTeacherConstant.OPENING_DATE, 0);
//        closingDate = intent.getLongExtra(WLXTeacherConstant.CLOSING_DATE, 0);
//        studentIds = intent.getStringExtra(WLXTeacherConstant.STUDENT_IDS);
//        isAddition = intent.getIntExtra(WLXTeacherConstant.IS_ADDITION, 0);
//        isFinished = intent.getIntExtra(WLXTeacherConstant.IS_FINISHED, 0);
        btnContent = intent.getStringExtra(WLXTeacherConstant.BUTTON_TEXT);
        currentTime = System.currentTimeMillis() / 1000L;
//        requestNet();
//        requstNetForSingleCourse();
//        initDataFormDatabase();
    }

    /**
     * 从数据库读取单个schedule
     */
    private void initDataFormDatabase() {
        singleScheduleList = WLXGreenDaoUtil.getScheduleDao().queryBuilder().where
                (wlx_scheduleDao.Properties.Grade_id.eq(gradeId), wlx_scheduleDao.Properties
                        .Schedule_id.eq(scheduleId)).list();
        prepare_content = singleScheduleList.get(0).getPrepare_content();
        is_finished = singleScheduleList.get(0).getIs_finished();
        is_study = singleScheduleList.get(0).getIs_study();
        opening_date = singleScheduleList.get(0).getOpening_date();
        closing_date = singleScheduleList.get(0).getClosing_date();
        addition_student_ids = singleScheduleList.get(0).getAddition_student_ids();
        WLXLogUtil.printE("is_finished---" + is_finished + "------opening_date----" +
                opening_date + "------closing_date" + closing_date);

        initView();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.iv_back_clazzroom_detail:                 //返回
                finish();
                break;
            case R.id.rl_clazzroom_call_roll:                   //点名
                String inClazzNums = inClazzTv.getText().toString().trim();
                String leaveNums = leaveTv.getText().toString().trim();
                String truantNums = truantTv.getText().toString().trim();

                //如果课程上课时间在当前时间半小时以后，点击时提示不能点名
                if (currentTime - opening_date > 1800) {
//                    Toast.makeText(WLXClazzRoomDetailActivity.this, "不能点名", Toast.LENGTH_SHORT)
//                            .show();
                    WLXCustomToast.show("不能点名");
                    //已经点过名,该课程是今天以前的课程，点击时提示已经点过
                } else if (currentTime > closing_date || (!inClazzNums.equals("0") || !leaveNums
                        .equals("0") || !truantNums.equals("0"))) {
//                    Toast.makeText(WLXClazzRoomDetailActivity.this, "已点名", Toast.LENGTH_SHORT)
//                            .show();
                    WLXCustomToast.show("已点名");
                } else {
                    startActivity(WLXCourseRollCallActivity.class);
                }
                break;
            case R.id.rl_course_content:  //课程内容
                if (TextUtils.isEmpty(prepare_content)) {
                    Intent intent = new Intent(this, WLXCourseContentActivity.class);
                    intent.putExtra(WLXTeacherConstant.SCHEDULE_ID, scheduleId);
                    startActivity(intent);
                } else {
                    WLXCustomToast.show("已经添加过内容");
                }
                break;
            case R.id.btn_end_course:
                if (is_finished == 0 && closing_date > currentTime) {
                    WLXCustomToast.show("不能结课");
                } else {
                    requstNetForCourseFinished();
                }
                break;
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        // TODO: 16/10/20
        requstNetForSingleCourse();
    }

    /**
     * 获取单个课程表信息
     */
    private void requstNetForSingleCourse() {
        WLXHttpRxHelper.getInstance().getSingleCourse(scheduleId, new
                Subscriber<WLXSingleCourseBean>() {
            @Override
            public void onCompleted() {
                initDataFormDatabase();
            }

            @Override
            public void onError(Throwable e) {
                onCompleted();
            }

            @Override
            public void onNext(WLXSingleCourseBean singleCourseBean) {
                if (singleCourseBean.getCode() == 0) {
                    saveScheduleTable(singleCourseBean);
                }
            }
        });
    }

    /**
     * 结课请求
     */
    private void requstNetForCourseFinished() {
        WLXLogUtil.printE("----gradeId------" + gradeId);
        WLXHttpRxHelper.getInstance().courseFinished(gradeId, scheduleId, new
                Subscriber<WLXCourseFinishedBean>() {


                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(WLXCourseFinishedBean finishedBean) {
                        if (finishedBean.getCode() == 0) {
                            endCourseBtn.setText("已结课");
                            endCourseBtn.setClickable(false);
                        }
                    }
                });
    }

    /**
     * 存储 wlx_schedule 表单
     *
     * @param singleCourseBean
     */
    private void saveScheduleTable(WLXSingleCourseBean singleCourseBean) {
        WLXSingleCourseBean.DataBean data = singleCourseBean.getData();
        String schedule_id = Integer.toString(data.getId());
        int teacher_user_id = data.getUser_id();
        int org_user_id = data.getOrg_user_id();
        int addition_id = data.getAddition_id();
        String addition_student_ids = data
                .getAddition_student_ids();
        int space_id = data.getSpace_id();
        int classroom_id = data.getClassroom_id();
        int grade_id = data.getGrade_id();
        String grade_title = data.getGrade_title();
        int score_well = data.getScore_well();
        int score_good = data.getScore_good();
        int score_bad = data.getScore_bad();
        String prepare_content = data.getPrepare_content();
        WLXLogUtil.printE("单个课程的课程内容:"+prepare_content );
        String remark = data.getRemark();
        String class_type_code = data.getClass_type().getCode();
        String class_child_type_code = data.getClass_child_type()
                .getCode();
        String grade_type_code = data.getGrade_type().getKey();
        int is_study = data.isIs_study() == true ? 1 : 0;
        int is_homework = data.isIs_homework() == true ? 1 : 0;
        int is_addition = data.isIs_addition() == true ? 1 : 0;
        int is_finished = data.isIs_finished() == true ? 1 : 0;
        String extend_info = new Gson().toJson(data.getExtend());

        long opening_date = WLXDateUtil.getStringToDate(data
                .getOpening_date());
        WLXLogUtil.printI(data.getOpening_date());
        long closing_date = WLXDateUtil.getStringToDate(data
                .getClosing_date());
        long schedule_date = WLXDateUtil.getStringToDate(data
                .getSchedule_date());
        long last_modified_date = WLXDateUtil.getStringToDate(data
                .getLast_modified_date());
        wlx_schedule wlxSchedule = new wlx_schedule(schedule_id,
                teacher_user_id, org_user_id,
                addition_id, addition_student_ids, space_id, classroom_id,
                grade_id, grade_title, score_well, score_good, score_bad,
                prepare_content, remark, class_type_code,
                class_child_type_code, grade_type_code, is_study,
                is_homework, is_addition, is_finished, extend_info,
                opening_date, closing_date, schedule_date, last_modified_date);
        List<wlx_schedule> wlx_schedules = WLXGreenDaoUtil
                .getScheduleDao().queryBuilder().where(wlx_scheduleDao
                        .Properties.Schedule_id.eq(schedule_id)).list();
        if (wlx_schedules.size() > 0) {
            if (last_modified_date > wlx_schedules.get(0)
                    .getLast_modified_date()) {
                WLXGreenDaoUtil.getScheduleDao().update(wlxSchedule);
            }
        } else {
            WLXGreenDaoUtil.getScheduleDao().insert(wlxSchedule);
        }
    }
}
